package gov.pbc.nn.kjgl.maintenance.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.uploader.DownloadFile;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileProvider;
import com.bstek.dorado.uploader.annotation.FileResolver;
import com.bstek.uflo.client.service.ProcessClient;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.service.StartProcessInfo;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.maintenance.entity.SysEmergencyScheme;
import gov.pbc.nn.kjgl.maintenance.entity.SysMaterial;

@Component
public class SysEmergencySchemePR_old {

	@Resource(name = CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao hibernateDao;
	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao coreHibernateDao;
	@Resource(name = ProcessClient.BEAN_ID)
	private ProcessClient processClient;
	@Resource(name = TaskClient.BEAN_ID)
	private TaskClient taskClient;

	@Autowired
	private SchemeJdbcDao schemeJdbcDao;
	@Autowired
	private  SysChangePR sysChangePR;

	@DataProvider
	public void loadSys(Page<SysEmergencyScheme> page, Criteria criteria) {
		schemeJdbcDao.loadSys(page, criteria);
	}

	@DataProvider
	public List<Map<String, Object>> getAssessor(String sysId) {
		return sysChangePR.loadCTO(sysId);
	}

	/**
	 * 删除 主子表
	 * 
	 * @param ls
	 */
	@Transactional
	@Expose
	public void deleteSys(List<String> ls) {
		for (String id : ls) {
			String fid = getFid(id).getSchemeFileId();
			this.hibernateDao.delete(fid, SysMaterial.class);
			this.hibernateDao.delete(id, SysEmergencyScheme.class);
		}
	}

	public SysEmergencyScheme getFid(String id) {
		String hql = "from SysEmergencyScheme where id=:id and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<SysEmergencyScheme> ls = this.hibernateDao.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		}
		return null;

	}

	/**
	 * 删除文件
	 * 
	 * @param id
	 * @return
	 */
	@Transactional
	@Expose
	public void delete(String id) {
		if (getFileById(id) != null) {
			this.hibernateDao.delete(id, SysMaterial.class);
		}
	}

	@DataResolver
	@Transactional
	public void save(List<SysEmergencyScheme> project) {
		for (SysEmergencyScheme pro : project) {
			EntityState state = EntityUtils.getState(pro);
			if (state.equals(EntityState.NEW)) {
				pro.setState(1);
				this.hibernateDao.save(pro);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.hibernateDao.update(pro);
			}
		}
	}

	@DataResolver
	@Transactional
	public void saveAndTJ(List<SysEmergencyScheme> project, String cto) {
		for (SysEmergencyScheme syser : project) {
			EntityState state = EntityUtils.getState(syser);
			if (state.equals(EntityState.NEW)) {
				syser.setState(1);
				this.hibernateDao.save(syser);
				this.commitKzSh(syser, cto);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.hibernateDao.update(syser);
			}
		}
	}

	/**
	 * 下载
	 * 
	 * @param parameter
	 * @return
	 * @throws IOException
	 */
	@FileProvider
	public DownloadFile download(Map<String, String> parameter) throws IOException {
		SysMaterial pfile = this.getFileById(parameter.get("id"));
		String fileName = pfile.getFileName();
		String path = pfile.getPath();
		InputStream stream = new FileInputStream(path);
		DownloadFile file = new DownloadFile(fileName, stream);
		return file;
	}

	public SysMaterial getFileById(String id) {
		String hql = "from SysMaterial where id=:id and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<SysMaterial> ls = this.hibernateDao.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		}
		return null;
	}

	/**
	 * 上传附件
	 *
	 * @param file
	 * @param parameter
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	@FileResolver
	public String upload(UploadFile file, Map<String, Object> parameter) throws Exception {
		String name = (String) parameter.get("name");
		String sysName = (String) parameter.get("sysName");
		String sysId = (String) parameter.get("sysId");
		String fid = (String) parameter.get("fid");
		String id = (String) parameter.get("id");

		String basePath = Configure.getString("SYS_YUNWEI_FILE_UPLOAD_PATH");
		if (StringUtils.isEmpty(basePath)) {
			throw new IllegalArgumentException("必须指定档案文件上传的基本地址");
		}
		String returnValue = "";
		try {
			if (this.check(name, fid)) {
				String pathArr = "应急预案文件";
				Path path = Paths.get(basePath, pathArr);
				if (!Files.isDirectory(path)) {
					path = Files.createDirectories(path);
				}
				path = path.resolve(UUID.randomUUID().toString());
				File destFile = Files.createFile(path).toFile();
				SysMaterial sm = this.saveFile(name, path.toString(), sysName, sysId);
				file.transferTo(destFile);
				returnValue = sm.getId();
			} else {
				returnValue = "error";
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	public synchronized boolean check(String filename, String fid) {
		String hql = "select COUNT(*) from SysMaterial where invalid=false and id=:fid and fileName=:fileName";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fileName", filename);
		map.put("fid", fid);
		int count = this.hibernateDao.queryForInt(hql, map);
		if (count == 0) {
			return true;
		} else {
			return false;
		}
	}

	public SysMaterial saveFile(String fileName, String path, String sysId, String sysName) {
		SysMaterial sm = new SysMaterial();
		sm.setSysId(sysId);
		sm.setSysName(sysName);
		sm.setFileName(fileName);
		sm.setPath(path);
		sm.setType(0);
		this.hibernateDao.save(sm);
		return sm;
	}

	/**
	 * 删除 附件
	 *
	 * @param list
	 * @throws IOException
	 */
	@Transactional
	@DataResolver
	public void deleteSysMaterial(List<SysMaterial> list) throws IOException {
		if (list != null) {
			for (SysMaterial pf : list) {
				this.hibernateDao.delete(pf);
			}
			for (SysMaterial pf : list) {
				String file = pf.getPath();
				Files.deleteIfExists(Paths.get(file));
			}
		}
	}

	/**
	 * 提交
	 * 
	 * @param syser
	 */
	@Transactional
	@Expose
	public void commitKzSh(SysEmergencyScheme syser, String cto) {
		try {
			// SysEmergencyScheme状态state 为5时表示审核中
			syser.setState(5);
			this.hibernateDao.update(syser);
			StartProcessInfo info = new StartProcessInfo();
			info.setPromoter(ContextHolder.getLoginUserName());
			info.setCompleteStartTask(true);
			info.setBusinessId(syser.getId());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cto", cto);
			map.put("sysId", syser.getSysId());
			map.put("agree", 1);
			info.setVariables(map);
			processClient.startProcessByName("应急预案", info);
		} catch (Exception e) {
			throw e;
			// TODO: handle exception
		}
	}

	/**
	 * 进行的保存。实际是做的是修改。（在次提交页面）
	 * 
	 * @param syses
	 */
	@Transactional
	@DataResolver
	public void saveRemtj(SysEmergencyScheme syses) {
		this.hibernateDao.update(syses);
	}

	/**
	 * 再次申请
	 * 
	 * @param taskId
	 * @param state
	 */
	@Expose
	public void ajaxRe(String taskId, String cto) {
		taskClient.start(Long.valueOf(taskId));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cto", cto);
		map.put("agree", 1);
		taskClient.complete(Long.valueOf(taskId), map);
	}

	/**
	 * 撤销申请
	 * 
	 * @param taskId
	 * @param project
	 */
	@Transactional
	@Expose
	public void cheXiao(String taskId, SysEmergencyScheme syses) {
		// PROJECT state设置为20,表示撤销流程
		syses.setState(20);
		this.hibernateDao.update(syses);
		taskClient.start(Long.valueOf(taskId));
		taskClient.forward(Long.valueOf(taskId), "结束");
	}

}
